#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
从 dictionary.ts 导入所有系统词典到数据库
"""

import json
import re
import pymysql
from datetime import datetime

DB_CONFIG = {
    'host': '127.0.0.1',
    'port': 3306,
    'user': 'root',
    'password': '123',
    'database': 'ry-vue',
    'charset': 'utf8mb4'
}

def parse_dictionary_ts(file_path):
    """解析 dictionary.ts 文件提取所有词典信息"""
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    dictionaries = []
    
    # 更精确的正则表达式，匹配整个词典对象
    # 匹配从 { 开始，包含 id, name, category, tags, url, length, language, languageCategory 等字段
    dict_pattern = r'\{[^}]*?id:\s*[\'"]([^\'"]+)[\'"][^}]*?\}'
    
    # 先找到所有可能的词典对象块
    matches = re.finditer(dict_pattern, content, re.DOTALL)
    
    for match in matches:
        dict_obj = match.group(0)
        
        # 提取各个字段
        id_match = re.search(r'id:\s*[\'"]([^\'"]+)[\'"]', dict_obj)
        name_match = re.search(r'name:\s*[\'"]([^\'"]+)[\'"]', dict_obj)
        desc_match = re.search(r'description:\s*[\'"]([^\'"]+)[\'"]', dict_obj)
        category_match = re.search(r'category:\s*[\'"]([^\'"]+)[\'"]', dict_obj)
        url_match = re.search(r'url:\s*[\'"]([^\'"]+)[\'"]', dict_obj)
        length_match = re.search(r'length:\s*(\d+)', dict_obj)
        language_match = re.search(r'language:\s*[\'"]([^\'"]+)[\'"]', dict_obj)
        lang_cat_match = re.search(r'languageCategory:\s*[\'"]([^\'"]+)[\'"]', dict_obj)
        tags_match = re.search(r'tags:\s*\[([^\]]*)\]', dict_obj)
        
        if not (id_match and name_match):
            continue
            
        dict_id = id_match.group(1)
        name = name_match.group(1)
        description = desc_match.group(1) if desc_match else ''
        category = category_match.group(1) if category_match else ''
        url = url_match.group(1) if url_match else ''
        length = int(length_match.group(1)) if length_match else 0
        language = language_match.group(1) if language_match else 'en'
        language_category = lang_cat_match.group(1) if lang_cat_match else 'en'
        
        # 解析tags
        tags = []
        if tags_match:
            tags_str = tags_match.group(1)
            if tags_str.strip():
                tag_matches = re.findall(r'[\'"]([^\'"]+)[\'"]', tags_str)
                tags = [tag.strip() for tag in tag_matches if tag.strip()]
        
        dictionaries.append({
            'id': dict_id,
            'name': name,
            'description': description,
            'category': category,
            'url': url,
            'length': length,
            'language': language,
            'languageCategory': language_category,
            'tags': tags
        })
    
    return dictionaries

def import_dictionaries():
    """导入所有词典到数据库"""
    ts_file = '/root/workspace/3.1.0-dev/work/aiword/src/resources/dictionary.ts'
    print(f"正在解析文件: {ts_file}\n")
    
    dictionaries = parse_dictionary_ts(ts_file)
    print(f"找到 {len(dictionaries)} 个词典定义\n")
    
    # 连接数据库
    conn = pymysql.connect(**DB_CONFIG)
    try:
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            # 获取现有词典
            cursor.execute("SELECT id FROM dict_book")
            existing_ids = {row['id'] for row in cursor.fetchall()}
            print(f"数据库中已有 {len(existing_ids)} 个词典\n")
            
            # 获取所有标签
            cursor.execute("SELECT id, name FROM dict_tag")
            tag_map = {row['name']: row['id'] for row in cursor.fetchall()}
            print(f"数据库中已有 {len(tag_map)} 个标签\n")
            
            inserted = 0
            updated = 0
            tag_created = 0
            
            print("=" * 80)
            print("开始导入词典...")
            print("=" * 80 + "\n")
            
            for dict_info in dictionaries:
                dict_id = dict_info['id']
                
                # 使用 INSERT ... ON DUPLICATE KEY UPDATE 来处理重复
                try:
                    cursor.execute("""
                        INSERT INTO dict_book 
                        (id, name, description, category, url, length, language, 
                         language_category, source_type, status, create_by, create_time)
                        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, '0', '0', 'system', NOW())
                        ON DUPLICATE KEY UPDATE
                        name = VALUES(name),
                        description = VALUES(description),
                        category = VALUES(category),
                        url = VALUES(url),
                        length = VALUES(length),
                        language = VALUES(language),
                        language_category = VALUES(language_category),
                        update_time = NOW()
                    """, (
                        dict_id, dict_info['name'], dict_info['description'],
                        dict_info['category'], dict_info['url'], dict_info['length'],
                        dict_info['language'], dict_info['languageCategory']
                    ))
                    
                    if dict_id in existing_ids:
                        updated += 1
                        action = "更新"
                    else:
                        inserted += 1
                        action = "新增"
                        existing_ids.add(dict_id)
                except Exception as e:
                    print(f"✗ 错误 {dict_id}: {e}")
                    continue
                
                # 处理标签
                if dict_info['tags']:
                    # 删除旧的标签关联
                    cursor.execute("DELETE FROM dict_book_tag WHERE book_id = %s", (dict_id,))
                    
                    # 为每个标签创建关联
                    for tag_name in dict_info['tags']:
                        # 确保标签存在
                        if tag_name not in tag_map:
                            cursor.execute(
                                "INSERT INTO dict_tag (name, create_by, create_time) VALUES (%s, 'system', NOW())",
                                (tag_name,)
                            )
                            tag_map[tag_name] = cursor.lastrowid
                            tag_created += 1
                        
                        # 创建关联
                        cursor.execute(
                            "INSERT IGNORE INTO dict_book_tag (book_id, tag_id) VALUES (%s, %s)",
                            (dict_id, tag_map[tag_name])
                        )
                    
                    print(f"✓ {action}: {dict_id} ({dict_info['name']}) - 标签: {', '.join(dict_info['tags'])}")
                else:
                    print(f"✓ {action}: {dict_id} ({dict_info['name']}) - 无标签")
            
            conn.commit()
            
            print()
            print("=" * 80)
            print("导入完成！")
            print("=" * 80)
            print(f"统计信息:")
            print(f"  - 新增词典: {inserted} 个")
            print(f"  - 更新词典: {updated} 个")
            print(f"  - 创建标签: {tag_created} 个")
            print(f"  - 总词典数: {len(dictionaries)} 个")
            print("=" * 80)
            
    except Exception as e:
        print(f"\n错误: {e}")
        import traceback
        traceback.print_exc()
        conn.rollback()
        raise
    finally:
        conn.close()

if __name__ == '__main__':
    import_dictionaries()

